package zhongbo.java.air.monitor.task;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import zhongbo.java.air.monitor.mapper.FlightActivityDailyMapper;
import zhongbo.java.air.monitor.model.dto.AirCraftDto;
import zhongbo.java.air.monitor.model.FlightActivityDaily;

import java.util.Date;
import java.util.List;

/**
 * 说明：
 *
 * @author 钟波dellNotebook
 * @since 2025年04月08日 星期二 04:12:59
 */
@Component
@Slf4j
public class AircraftActivityTask {

    @Autowired
    private FlightActivityDailyMapper flightActivityDailyMapper;

    // 每10分钟执行（注意配置时区）
    @Scheduled(
            // 开发中可设置短一点, 这里设置5分钟
            fixedDelay = 5 * 60 * 1000
            // 启动后等多少毫秒, 执行第一次定时任务, 这里设置5秒
            , initialDelay = 5000
    )
    public void updateDailyActivity() {
        log.info("---- 执行定时任务 -----");
        doJob();
    }

    private void doJob() {
        String today = DateUtil.formatDate(new Date());
        // 1. 从轨迹表查询当天出现过的ICAO码（需实现轨迹表查询逻辑）
        List<FlightActivityDaily> activeICaos = flightActivityDailyMapper.selectDailyStats(today);
        log.info("查询结果: {}条", activeICaos.size());
        // 2. 批量插入或更新
        // todo 周二任务: 存入数据库. 存入之前先icao+date两个字段, 判断数据库是否已有数据, 有的话则是更新
        LambdaQueryWrapper<FlightActivityDaily> lambdaQueryWrapper = new LambdaQueryWrapper<>();

        activeICaos.forEach(activeICao ->{
            /**
             * 查询飞机字典表
             */
            AirCraftDto airCrafts = flightActivityDailyMapper.selectAirCraft(activeICao.getIcaoCode());

            if (airCrafts != null) {
                /**
                 * 补充字段
                 */
                activeICao.setRegistration(airCrafts.getRegistration());
                activeICao.setAirline(airCrafts.getAirline());
                activeICao.setAircraftType(airCrafts.getAircraftType());
            }

            lambdaQueryWrapper.clear();
            lambdaQueryWrapper.eq(FlightActivityDaily::getIcaoCode,activeICao.getIcaoCode());
            lambdaQueryWrapper.eq(FlightActivityDaily::getDate,activeICao.getDate());
            if (!flightActivityDailyMapper.selectList(lambdaQueryWrapper).isEmpty()){
                flightActivityDailyMapper.updateById(activeICao);
            }else {
                flightActivityDailyMapper.insert(activeICao);
                activeICao.setCreatedTime(new Date());
            }
            activeICao.setUpdatedTime(new Date());
        });
    }

}
